# -*- coding: utf-8 -*-
"""
@author: Junxiao Song
"""

from __future__ import print_function
import numpy as np

"""棋盘"""
class Board(object):
    """board for the game"""

    def __init__(self, **kwargs):
        # 棋盘宽
        self.width = int(kwargs.get('width', 8))
        # 棋盘高
        self.height = int(kwargs.get('height', 8))
        # board states stored as a dict,
        # key: move as location on the board,
        # value: player as pieces type
        # 棋盘状态{key=棋盘位置，value=玩家ID}
        self.states = {}
        # need how many pieces in a row to win
        # 多少棋子连成线为赢
        self.n_in_row = int(kwargs.get('n_in_row', 5))
        # 玩家列表
        self.players = [1, 2]  # player1 and player2

    """初始化棋盘"""
    def init_board(self, start_player=0):
        # 棋盘的宽度和高度都不能小于赢需要连线子数
        if self.width < self.n_in_row or self.height < self.n_in_row:
            raise Exception('board width and height can not be '
                            'less than {}'.format(self.n_in_row))
        # 当前玩家为开始玩家
        self.current_player = self.players[start_player]  # start player
        # keep available moves in a list
        # 有效位置，转为列表
        self.availables = list(range(self.width * self.height))
        # 状态
        self.states = {}
        # 上一走子
        self.last_move = -1
    #走子到位置
    def move_to_location(self, move):
        """
        3*3 board's moves like:
        6 7 8
        3 4 5
        0 1 2
        and move 5's location is (1,2)

        3*3 棋盘的走子:
        6 7 8
        3 4 5
        0 1 2
        走子到5的位置是(1,2)
        """
        # 高，宽
        h = move // self.width
        w = move % self.width
        return [h, w]
    # 位置到走子
    def location_to_move(self, location):
        if(len(location) != 2):
            return -1
        h = location[0]
        w = location[1]
        move = h * self.width + w
        if(move not in range(self.width * self.height)):
            return -1
        return move

    # 当前状态
    def current_state(self):
        """return the board state from the perspective of the current player.
        state shape: 4*width*height
        以当玩家的视角，返回棋盘状态
        状态开关：4*宽*高
        """
        # 初始化方阵state (4*宽*高)
        square_state = np.zeros((4, self.width, self.height))
        # 状态是否不为空
        if self.states:
            moves, players = np.array(list(zip(*self.states.items())))
            move_curr = moves[players == self.current_player]
            move_oppo = moves[players != self.current_player]
            square_state[0][move_curr // self.width,
                            move_curr % self.height] = 1.0
            square_state[1][move_oppo // self.width,
                            move_oppo % self.height] = 1.0
            # indicate the last move location
            square_state[2][self.last_move // self.width,
                            self.last_move % self.height] = 1.0
        # 状态是否为偶数
        if len(self.states) % 2 == 0:
            square_state[3][:, :] = 1.0  # indicate the colour to play

        # 返回方阵状态
        return square_state[:, ::-1, :]

    # 执行走子
    def do_move(self, move):
        # 状态[走子] = 当前玩家ID
        self.states[move] = self.current_player
        # 移出一种走子可能
        self.availables.remove(move)
        # 交换当前玩家
        self.current_player = (
            self.players[0] if self.current_player == self.players[1]
            else self.players[1]
        )
        # 上一走子
        self.last_move = move

    # 检查是否出现了赢家，玩家ID是多少,没有则返回 False, -1
    def has_a_winner(self):
        width = self.width
        height = self.height
        states = self.states
        n = self.n_in_row

        # 已经走子列表
        moved = list(set(range(width * height)) - set(self.availables))
        # 基本步数都不够， 直接返回无赢家
        if(len(moved) < self.n_in_row + 2):
            return False, -1

        # 循环判断是否有赢家了
        for m in moved:
            h = m // width
            w = m % width
            player = states[m]

            if (w in range(width - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n))) == 1):
                return True, player

            if (h in range(height - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n * width, width))) == 1):
                return True, player

            if (w in range(width - n + 1) and h in range(height - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n * (width + 1), width + 1))) == 1):
                return True, player

            if (w in range(n - 1, width) and h in range(height - n + 1) and
                    len(set(states.get(i, -1) for i in range(m, m + n * (width - 1), width - 1))) == 1):
                return True, player

        return False, -1

    # 检查是否达到游戏结束条件, 返回是否结束， 玩家1,2,或者-1
    def game_end(self):
        """Check whether the game is ended or not"""
        # 是否已经有玩家了
        win, winner = self.has_a_winner()
        if win:
            return True, winner
        elif not len(self.availables):
            return True, -1
        return False, -1

    def get_current_player(self):
        return self.current_player

# 游戏服务器
class Game(object):
    """game server"""

    #初始化
    def __init__(self, board, **kwargs):
        self.board = board

    # 绘图
    def graphic(self, board, player1, player2):
        """Draw the board and show game info"""
        # 绘制棋盘
        width = board.width
        height = board.height

        print("Player", player1, "with X".rjust(3))
        print("Player", player2, "with O".rjust(3))
        print()
        # 绘制列头
        for x in range(width):
            print("{0:8}".format(x), end='')
        print('\r\n')
        # 内容各行
        for i in range(height - 1, -1, -1):
            print("{0:4d}".format(i), end='')
            for j in range(width):
                loc = i * width + j
                p = board.states.get(loc, -1)
                if p == player1:
                    print('X'.center(8), end='')
                elif p == player2:
                    print('O'.center(8), end='')
                else:
                    print('_'.center(8), end='')
            print('\r\n\r\n')

    # 开始游戏
    def start_play(self, player1, player2, start_player=0, is_shown=1):
        """start a game between two players"""
        # 开始游戏，检查先手玩家索引
        if start_player not in (0, 1):
            raise Exception('start_player should be either 0 (player1 first) '
                            'or 1 (player2 first)')
        # 初始化棋盘
        self.board.init_board(start_player)
        # 取得玩家1，2
        p1, p2 = self.board.players
        # 设置玩家ID
        player1.set_player_ind(p1)
        player2.set_player_ind(p2)
        # 玩家词典{id=玩家对象｝。 **数字也是可以作KEY
        players = {p1: player1, p2: player2}
        # 是否显示对弈
        if is_shown:
            self.graphic(self.board, player1.player, player2.player)

        while(1):
            # 取得当前玩家ID
            current_player = self.board.get_current_player()
            # 取得走子玩家对象
            player_in_turn = players[current_player]
            # 取得走子
            move = player_in_turn.get_action(self.board)
            # 走子
            self.board.do_move(move)
            # 显示走子
            if is_shown:
                self.graphic(self.board, player1.player, player2.player)
            #检查是否游戏结束，胜者
            end, winner = self.board.game_end()
            if end:
                # 是否展示
                if is_shown:
                    if winner != -1:
                        print("Game end. Winner is", players[winner])
                    else:
                        print("Game end. Tie")
                return winner

    # 开始自我对弈
    def start_self_play(self, player, is_shown=0, temp=1e-3):
        """ start a self-play game using a MCTS player, reuse the search tree,
        and store the self-play data: (state, mcts_probs, z) for training
        开始自我对弈游戏，采用一个MCTS玩家，使用搜索， 并存储自我对弈数据
        (状态 局面，mcts概率, z对弈结果)作为训练数据， 其中s,z 都需要以当
        前玩家的视角去看待
        """
        # 初始化棋盘
        self.board.init_board()
        # 取得玩家ID
        p1, p2 = self.board.players
        # 初始化，状态，MCTS概率， 当前玩家
        states, mcts_probs, current_players = [], [], []
        while(1):
            # 取得走子，与走子概率
            move, move_probs = player.get_action(self.board,
                                                 temp=temp,
                                                 return_prob=1)
            # store the data
            #  存储数据(追加当前状态）
            states.append(self.board.current_state())
            # 存储走子概率
            mcts_probs.append(move_probs)
            # 存储当前玩家
            current_players.append(self.board.current_player)
            # perform a move
            # 执行走子(这里会切换玩家ID)
            self.board.do_move(move)
            # 是否显示
            if is_shown:
                self.graphic(self.board, p1, p2)
            end, winner = self.board.game_end()
            if end:
                # winner from the perspective of the current player of each state
                # 每个状态的当前玩家的视角的赢家
                winners_z = np.zeros(len(current_players))
                # 出现有胜者
                if winner != -1:
                    winners_z[np.array(current_players) == winner] = 1.0
                    winners_z[np.array(current_players) != winner] = -1.0
                # reset MCTS root node
                # 重置玩家
                player.reset_player()
                # 是否显示
                if is_shown:
                    if winner != -1:
                        print("Game end. Winner is player:", winner)
                    else:
                        print("Game end. Tie")
                return winner, zip(states, mcts_probs, winners_z)